package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Autowired
    private UserMapper userMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 验证手机号格式，生成并发送验证码
     * */
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.验证手机号的合法性
        if (RegexUtils.isPhoneInvalid(phone)){
            //非法
            return Result.fail("手机号的格式错误!");
        }
        //2.生成随机6位数验证码
        String code = RandomUtil.randomNumbers(6);
        //3.发送验证码
//        session.setAttribute("code", code);
        //将验证码存到redis中
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        log.debug("验证码发送成功{}",code);
        return Result.ok();
    }

    /**
     * 实现登录功能
     * */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.校验手机号
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号不合法，请重新输入!");
        }
        //2.校验验证码
        //3.如果验证码不一致，报错
        String code = loginForm.getCode();
//        Object cacheCode = session.getAttribute("code");
        //从redis中取验证码
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        if (cacheCode == null || !cacheCode.equals(code)){
            return Result.fail("验证码有误, 请核对后重试！");
        }
        //4.如果一致则根据手机号查询用户
        User user = query().eq("phone", phone).one();
        //5.用户不存在，注册并保存数据库
        if (user == null) {
            user = createUserWithPhone(phone);
        }
        //保存用户信息到redis,随机生成uuid作为token
        String token = UUID.randomUUID().toString(true);
        //将user用户存到userdto中
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        //将userDto妆转化为map集合
        Map<String, Object> userDTOMap = BeanUtil.beanToMap(
                userDTO,
                new HashMap<>(), // 目标Map
                CopyOptions.create() // 复制配置
                        .setIgnoreNullValue(true) // 可选：忽略null值，避免存入无效数据
                        .setFieldValueEditor((fieldName, fieldValue) ->
                                fieldValue.toString() // 可选：将字段值转换为字符串，避免存入对象
                        )
        );
        String strToken = LOGIN_USER_KEY + token;
        //存入redis
        stringRedisTemplate.opsForHash().putAll(strToken, userDTOMap);
        //设置token过期时间
        stringRedisTemplate.expire(strToken, 30, TimeUnit.MINUTES);
//        session.setAttribute("user", BeanUtil.copyProperties(user, UserDTO.class));
        return Result.ok(token);
    }

    //创建user对象
    private User createUserWithPhone(String phone){
        //创建user对象
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        save(user);
        return user;
    }
}
